package com.qf.service.Impl;

import com.alibaba.druid.util.StringUtils;
import com.qf.dao.UserDao;
import com.qf.dao.impl.UserDaoImpl;
import com.qf.exceptions.MyBaseException;
import com.qf.pojo.TbUser;
import com.qf.service.UserService;
import com.qf.utils.DBUtils;
import com.qf.utils.ExcutorsUtils;
import com.qf.utils.MD5Utils;
import com.qf.utils.MaiUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private static UserDao userDao;
    @Override
    public void addUser(TbUser user) {
        if (!user.getEmail().matches("^[A-Za-z0-9\\u4e00-\\u9fa5]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$")) {
            System.err.println("邮箱格式不匹配");
            throw new MyBaseException("邮箱不和规则");
        }
        if (!user.getPassword().matches("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z\\\\W]{6,18}$")){
            System.err.println("密码格式不对");
            throw new MyBaseException("密码格式不对");
        }

        String password = user.getPassword();
        String md5 = MD5Utils.md5(password);
        user.setPassword(md5);
        String code  = UUID.randomUUID().toString().replace("-","");
        user.setCode(code);
        userDao.addUser(user);

        ExcutorsUtils.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    MaiUtils.sendMail(user);
                } catch (MessagingException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    @Override
    public int active(String username, String code) throws Exception {
        return userDao.active(username,code);
    }

    @Override
    public TbUser login(String username, String password) throws Exception {
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            return null;
        }
        TbUser tbUser = userDao.findUserByName(username);
        if (tbUser == null){
            return null;
        }
        String md5 = MD5Utils.md5(password);
        if (md5.equals(tbUser.getPassword())){
            return tbUser;
        }
        DBUtils.close();
        return null;
    }
}
